<?php

declare(strict_types=1);
/*
 * @Description: 企业微信service类
 * @Author: QianLong
 * @Date: 2019-10-13 12:39:05
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-04-23 12:00:13
 */

namespace App\Service\Push;

use App\Common\RedisCache;
use App\Service\Common;
use Yurun\Util\HttpRequest;

class WxWork
{
    protected $serverInfo = [];
    protected $http = null;
    protected $redisCache = null;
    public function __construct($serverInfo)
    {
        $this->serverInfo = $serverInfo;
        $this->http = new HttpRequest;
        $this->redisCache = new RedisCache();
        if (isset($serverInfo['ww_apps_from']) && $serverInfo['ww_apps_from'] =='platform' && isset($serverInfo['ww_id'])) {
            $wwInfo = $this->redisCache->getWxWorkInfo($serverInfo['ww_id']);
            $this->serverInfo['platform_alert_weixin_app_corpid'] = $wwInfo['crop_id'];
            $this->serverInfo['platform_alert_weixin_app_agentid'] = $wwInfo['agent_id'];
            $this->serverInfo['platform_alert_weixin_app_secret'] = $wwInfo['secret'];
            unset($wwInfo);
        }
    }

    /**
     * 企业微信机器人
     */
    public function pushBotText(array $params)
    {
        $postWWork['msgtype'] = 'text';
        $postWWork['text']['content'] = $params['msg_content'];
        if (!isset($params['atMobiles']) && !empty($params['atMobiles'])) {
            $postWWork['text']['mentioned_mobile_list'] = explode(',', $params['atMobiles']);
            foreach ($postWWork['text']['mentioned_mobile_list'] as $key => $vo) {
                if (!empty($vo)) {
                    if ($vo == 'all') {
                        $postWWork['text']['mentioned_mobile_list'][$key] = '@all';
                    }
                }
            }
        }
        $response = $this->http->post($this->serverInfo['platform_alert_weixin_work_webhook_url'], $postWWork, 'json');
        return json_decode($response->body(), true);
    }
    public function pushBotImage(array $params)
    {
        $postWWork['msgtype'] = 'image';
        $postWWork['image']['base64'] = base64_encode($params['msg_content']);
        $postWWork['image']['md5'] = md5_file($params['msg_content']);
        if (!isset($params['atMobiles']) && !empty($params['atMobiles'])) {
            $postWWork['text']['mentioned_mobile_list'] = explode(',', $params['atMobiles']);
            foreach ($postWWork['text']['mentioned_mobile_list'] as $key => $vo) {
                if (!empty($vo)) {
                    if ($vo == 'all') {
                        $postWWork['text']['mentioned_mobile_list'][$key] = '@all';
                    }
                }
            }
        }
        $response = $this->http->post($this->serverInfo['platform_alert_weixin_work_webhook_url'], $postWWork, 'json');
        return json_decode($response->body(), true);
    }
    public function pushBotTuwen(array $params)
    {
        $postWWork['msgtype'] = 'news';
        $postWWork['news']['articles'][0]['title'] = $params['title'];
        $postWWork['news']['articles'][0]['description'] = $params['content'];
        $msgContent = json_decode($params['msg_content'], true);
        $postWWork['news']['articles'][0]['url'] = isset($msgContent['url']) ? $msgContent['url'] : '';
        $postWWork['news']['articles'][0]['picurl'] = isset($msgContent['pic']) ? $msgContent['pic'] : '';
        $response = $this->http->post($this->serverInfo['platform_alert_weixin_work_webhook_url'], $postWWork, 'json');
        return json_decode($response->body(), true);
    }
    public function pushBotMD(array $params)
    {
        $file = BASE_PATH . '/runtime/dev_ww.txt';
        file_put_contents($file, 'start' . "\r\n", FILE_APPEND);
        $postWWork['msgtype'] = 'markdown';
        $postWWork['markdown']['content'] = $params['msg_content'];
        $mentioned_mobile_list = [];
        if (!isset($params['atMobiles']) && !empty($params['atMobiles'])) {
            $mentioned_mobile_list = explode(',', $params['atMobiles']);
        }else if(isset($this->serverInfo['platform_alert_weixin_work_webhook_touser']) && !empty($this->serverInfo['platform_alert_weixin_work_webhook_touser'])){
            $mentioned_mobile_list = explode('|', $this->serverInfo['platform_alert_weixin_work_webhook_touser']);
        }
        file_put_contents($file, json_encode($mentioned_mobile_list) . "\r\n", FILE_APPEND);
        if (!empty($mentioned_mobile_list)) {
            foreach ($mentioned_mobile_list as $key => $vo) {
                if (!empty($vo)) {
                    if ($vo == 'all') {
                        $mentioned_mobile_list[$key] = '<@all>';
                    }else{
                        $mentioned_mobile_list[$key] = '<@' . $vo . '>';
                    }
                }
            }
            file_put_contents($file, json_encode($mentioned_mobile_list) . "\r\n", FILE_APPEND);
            $postWWork['markdown']['content'] = $postWWork['markdown']['content'] . implode('', $mentioned_mobile_list);
        }
        file_put_contents($file, json_encode($postWWork) . "\r\n", FILE_APPEND);
        $response = $this->http->post($this->serverInfo['platform_alert_weixin_work_webhook_url'], $postWWork, 'json');
        return json_decode($response->body(), true);
    }
    /**
     * 企业应用
     */
    public function pushAppText(array $params)
    {
        $postWWorkApp['msgtype'] = 'text';
        $postWWorkApp['agentid'] = $this->serverInfo['platform_alert_weixin_app_agentid'];
        $postWWorkApp['text']['content'] = $params['msg_content'];
        if (!isset($params['toUser']) && !empty($params['toUser'])) {
            $postWWorkApp['touser'] = $params['toUser'];
        } else {
            $postWWorkApp['touser'] = $this->serverInfo['platform_alert_weixin_app_touser'];
        }
        $toUserList = explode('|', $postWWorkApp['touser']);
        $common = new Common;
        if (!empty($toUserList)) {
            $mentioned_user_id_list = [];
            foreach ($toUserList as $key => $vo) {
                if ($common->validatePhoneNumber($vo)) {
                    $userid = $this->getPhoneUserId($vo);
                    if (!empty($userid)) {
                        $mentioned_user_id_list[] = $userid;
                    }
                } else {
                    $mentioned_user_id_list[] = $vo;
                }
            }
            if (!empty($mentioned_user_id_list)) {
                $postWWorkApp['touser'] = implode('|', $mentioned_user_id_list);
            }
        }
        if (!isset($params['atParty']) && !empty($params['atParty'])) {
            $postWWorkApp['toparty'] = $params['atParty'];
        } else {
            $postWWorkApp['toparty'] = $this->serverInfo['platform_alert_weixin_app_toparty'];
        }
        $token = $this->redisCache->getWxWorkAccessToken($this->serverInfo['platform_alert_weixin_app_corpid'],$this->serverInfo['platform_alert_weixin_app_agentid'], $this->serverInfo['platform_alert_weixin_app_secret']);
        $response = $this->http->post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . $token, $postWWorkApp, 'json');
        return json_decode($response->body(), true);
    }
    public function getPhoneUserId(string $phone)
    {
        $postWWorkApp['mobile'] = $phone;
        $token = $this->redisCache->getWxWorkAccessToken($this->serverInfo['platform_alert_weixin_app_corpid'],$this->serverInfo['platform_alert_weixin_app_agentid'], $this->serverInfo['platform_alert_weixin_app_secret']);
        $response = $this->http->post('https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=' . $token, $postWWorkApp, 'json');
        $result = json_decode($response->body(), true);
        
        if ($result['errcode'] == 0) {
            return $result['userid'];
        }
        return '';
    }
    public function pushAppImage(array $params)
    {
        $postWWorkApp['msgtype'] = 'image';
        $postWWorkApp['agentid'] = $this->serverInfo['platform_alert_weixin_app_agentid'];
        $postWWorkApp['text']['content'] = $params['msg_content'];
        if (!isset($params['toUser']) && !empty($params['toUser'])) {
            $postWWorkApp['touser'] = $params['toUser'];
        } else {
            $postWWorkApp['touser'] = $this->serverInfo['platform_alert_weixin_app_touser'];
        }
        $toUserList = explode('|', $postWWorkApp['touser']);
        $common = new Common;
        if (!empty($toUserList)) {
            $mentioned_user_id_list = [];
            foreach ($toUserList as $key => $vo) {
                if ($common->validatePhoneNumber($vo)) {
                    $userid = $this->getPhoneUserId($vo);
                    if (!empty($userid)) {
                        $mentioned_user_id_list[] = $userid;
                    }
                } else {
                    $mentioned_user_id_list[] = $vo;
                }
            }
            if (!empty($mentioned_user_id_list)) {
                $postWWorkApp['touser'] = implode('|', $mentioned_user_id_list);
            }
        }
        if (!isset($params['atParty']) && !empty($params['atParty'])) {
            $postWWorkApp['toparty'] = $params['atParty'];
        } else {
            $postWWorkApp['toparty'] = $this->serverInfo['platform_alert_weixin_app_toparty'];
        }
        $token = $this->redisCache->getWxWorkAccessToken($this->serverInfo['platform_alert_weixin_app_corpid'],$this->serverInfo['platform_alert_weixin_app_agentid'], $this->serverInfo['platform_alert_weixin_app_secret']);
        $response = $this->http->post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . $token, $postWWorkApp, 'json');
        return json_decode($response->body(), true);
    }
    public function pushAppTuwen(array $params)
    {
        $postWWorkApp['msgtype'] = 'news';
        $postWWorkApp['agentid'] = $this->serverInfo['platform_alert_weixin_app_agentid'];
        $postWWorkApp['news']['articles'][0]['title'] = $params['title'];
        $postWWorkApp['news']['articles'][0]['description'] = $params['content'];
        $msgContent = json_decode($params['msg_content'], true);
        $postWWorkApp['news']['articles'][0]['url'] = isset($msgContent['url']) ? $msgContent['url'] : '';
        $postWWorkApp['news']['articles'][0]['picurl'] = isset($msgContent['pic']) ? $msgContent['pic'] : '';
        if (!isset($params['toUser']) && !empty($params['toUser'])) {
            $postWWorkApp['touser'] = $params['toUser'];
        } else {
            $postWWorkApp['touser'] = $this->serverInfo['platform_alert_weixin_app_touser'];
        }
        $toUserList = explode('|', $postWWorkApp['touser']);
        $common = new Common;
        if (!empty($toUserList)) {
            $mentioned_user_id_list = [];
            foreach ($toUserList as $key => $vo) {
                if ($common->validatePhoneNumber($vo)) {
                    $userid = $this->getPhoneUserId($vo);
                    if (!empty($userid)) {
                        $mentioned_user_id_list[] = $userid;
                    }
                } else {
                    $mentioned_user_id_list[] = $vo;
                }
            }
            if (!empty($mentioned_user_id_list)) {
                $postWWorkApp['touser'] = implode('|', $mentioned_user_id_list);
            }
        }
        if (!isset($params['atParty']) && !empty($params['atParty'])) {
            $postWWorkApp['toparty'] = $params['atParty'];
        } else {
            $postWWorkApp['toparty'] = $this->serverInfo['platform_alert_weixin_app_toparty'];
        }
        $token = $this->redisCache->getWxWorkAccessToken($this->serverInfo['platform_alert_weixin_app_corpid'],$this->serverInfo['platform_alert_weixin_app_agentid'], $this->serverInfo['platform_alert_weixin_app_secret']);
        $response = $this->http->post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . $token, $postWWorkApp, 'json');
        return json_decode($response->body(), true);
    }
    public function pushAppMD(array $params)
    {
        $postWWorkApp['msgtype'] = 'markdown';
        $postWWorkApp['agentid'] = $this->serverInfo['platform_alert_weixin_app_agentid'];
        $postWWorkApp['markdown']['content'] = $params['msg_content'];
        if (!isset($params['toUser']) && !empty($params['toUser'])) {
            $postWWorkApp['touser'] = $params['toUser'];
        } else {
            $postWWorkApp['touser'] = $this->serverInfo['platform_alert_weixin_app_touser'];
        }
        $toUserList = explode('|',$postWWorkApp['touser']);
        $common = new Common;
        if (!empty($toUserList)) {
            $mentioned_user_id_list = [];
            foreach ($toUserList as $key => $vo) {
                if ($common->validatePhoneNumber($vo)) {
                    $userid = $this->getPhoneUserId($vo);
                    if (!empty($userid)) {
                        $mentioned_user_id_list[] = $userid;
                    }
                }else{
                    $mentioned_user_id_list[] = $vo;
                }
            }
            if (!empty($mentioned_user_id_list)) {
                $postWWorkApp['touser'] = implode('|',$mentioned_user_id_list);
            }
        }
        if (!isset($params['atParty']) && !empty($params['atParty'])) {
            $postWWorkApp['toparty'] = $params['atParty'];
        } else {
            $postWWorkApp['toparty'] = $this->serverInfo['platform_alert_weixin_app_toparty'];
        }
        $token = $this->redisCache->getWxWorkAccessToken($this->serverInfo['platform_alert_weixin_app_corpid'],$this->serverInfo['platform_alert_weixin_app_agentid'], $this->serverInfo['platform_alert_weixin_app_secret']);
        $response = $this->http->post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . $token, $postWWorkApp, 'json');
        return json_decode($response->body(), true);
    }
}
